import { reactive, ref } from 'vue'

function defaultClone(obj: any) {
  if (obj === null || typeof obj !== 'object') return obj
  return JSON.parse(JSON.stringify(obj))
}
type Resettable<T> = [T, () => void] & { state: T, reset: () => void }
export function useResettableRef<T>(value: T, clone = defaultClone): Resettable<T> {
  const initValue = clone(value)
  const state = ref(value)
  const reset = () => {
    state.value = clone(initValue)
  }
  return Object.assign([state, reset], { state, reset }) as unknown as Resettable<T>
}

export function useResettableReactive<T extends object>(value: T, clone = defaultClone): Resettable<T> {
  const state = reactive(clone(value)) as T
  const reset = () => {
    Object.keys(state).forEach(key => delete state[key as keyof T])
    Object.assign(state, clone(value))
  }
  return Object.assign([state, reset], { state, reset }) as unknown as Resettable<T>
}

// const { state, reset } = useResettableReactive({ a: 1, v: 2 })
// const [state, reset] = useResettableReactive({ a: 1, v: 2 })
